package com.tripspins.app.helper;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

/**
 * Created by João.Rutkoski on 11/03/14.
 */
public class SensorsHelper implements SensorEventListener {

    private SensorsHelper sensorsHelper;
    private Sensor pressureSensor;
    private Sensor temperatureSensor;
    private SensorManager sensorManager;
    private Context context;
    private LocationHelper locationHelper;
    private float pressure;
    private float temperature;

    public SensorsHelper getInstance(Context context)
    {
        if(sensorsHelper == null)
            sensorsHelper = new SensorsHelper(context);
        return sensorsHelper;
    }

    private SensorsHelper(Context context)
    {
        this.context = context;
        sensorManager = (SensorManager)context.getSystemService(context.SENSOR_SERVICE);
        pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        temperatureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
        if(pressureSensor != null)
            sensorManager.registerListener(this,pressureSensor, SensorManager.SENSOR_DELAY_NORMAL);
        //locationHelper = LocationHelper.getInstance(context, map);

    }

    public double getAltitude()
    {
        if(pressureSensor == null)
        {
            return locationHelper.getAltitude();
        }
        else
            return SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, pressure);
    }

    public float getSpeed()
    {
        return locationHelper.getSpeed();
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {

        switch (sensorEvent.sensor.getType()){
            case Sensor.TYPE_PRESSURE:
                pressure = sensorEvent.values[0];
                break;
            case Sensor.TYPE_AMBIENT_TEMPERATURE:
                temperature = sensorEvent.values[0];//temperature in Celsius
                break;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }
}
